import * as types from './mutation-type'
import api from '../../api/editor'
import Page from '../../model/Page'
import Theme from '../../model/Theme'
import Element from '../../model/Element'
import tools from '../../util/tools'
import httpRequest from '@/utils/httpRequest'

/**
 * 保存页面数据
 */
export const saveTheme = ({commit}, theme) => {
  if (theme && theme.id) {
    return Promise.resolve(api.updateTheme(theme).then((res) => {
      commit(types.UPDATE_THEME_SUCCESS, res)
    }))
  } else {
    return Promise.resolve(api.saveTheme(theme).then((res) => {
      commit(types.ADD_THEME_SUCCESS, res)
    }))
  }
}

export const saveSkin = ({commit}, theme) => {
  theme.elements = theme.pages[0].elements
  if (theme && theme.id) {
    return Promise.resolve(api.updateSkin(theme).then((res) => {
      commit(types.UPDATE_THEME_SUCCESS, res)
    }))
  } else {
    return Promise.resolve(api.saveSkin(theme).then((res) => {
      commit(types.ADD_THEME_SUCCESS, res)
    }))
  }
}

/**
 * 获取用户所有场景主题
 * @param commit
 */
export const getUserThemeList = ({commit}, type) => {
  api.getUserThemeList(type).then((res) => {
    commit(types.GET_USER_THEME_LIST, res)
  })
}

/**
 * 创建场景主题
 * @param commit
 */

export const createTheme = ({commit}, type) => {
  var theme = new Theme({type: type})
  commit(types.CREATE_THEME, theme)
  commit(types.SET_CUR_EDITOR_THEME, theme)
}

/**
 * 设置当前编辑的主题
 */
export const setEditorTheme = ({commit}, theme) => {
  var newTheme = new Theme(theme)
  commit(types.SET_CUR_EDITOR_THEME, newTheme)
}

/**
 * 设置当前正在编辑的页面
 * @param commit
 * @param page
 */
export const setEditorPage = ({commit}, page) => {
  commit(types.SET_CUR_EDITOR_PAGE, page)
}

/**
 * 给主题添加页面
 * @param commit
 */
export const addPage = ({commit}) => {
  var page = new Page()
  commit(types.ADD_PAGE, page)
  commit(types.SET_CUR_EDITOR_PAGE, page)
}

/**
 * 添加页面元素
 */
export const addElement = ({commit, state}, data) => {
  commit(types.ADD_PIC_ELEMENT, new Element(data))
  var list = state.editorPage.elements
  var lastIndex = list.length - 1
  list[lastIndex]['zindex'] = lastIndex ? list[lastIndex - 1]['zindex'] + 1 : 1
  commit(types.SET_CUR_EDITOR_ELEMENT, state.editorPage.elements[lastIndex])
}

/**
 * 添加背景图片
 */
export const addBGElement = ({commit}, data) => {
  var element = new Element(data)
  commit(types.SET_BG_ELEMENT, element)
  commit(types.SET_CUR_EDITOR_ELEMENT, null)
}

/**
 * 保存图片
 * @param commit
 * @param data
 */
export const savePic = ({commit}, data) => {

      console.log(data);
  httpRequest({
    url: httpRequest.adornUrl(`/sys/material/save`),
    method: 'post',
    data: httpRequest.adornData(
      {
        cid: data.cid,
        filePath: data.filePath,
        name: '临时上传' + new Date().getTime(),
        fileSize: data.size,
        fileName: data.name,
        type: 2,
        width: data.width,
        height: data.height
      }
    )
  }).then(({data}) => {
    if (data && data.code === 0) {
      console.log('已添加素材')
    } else {
    }
  })
  commit(types.PUSH_PIC_LIST, data)
}

/**
 * 保存视频
 * @param commit
 * @param data
 */
export const saveVideo = ({commit}, data) => {

      console.log(data);
  httpRequest({
    url: httpRequest.adornUrl(`/sys/material/save`),
    method: 'post',
    data: httpRequest.adornData(
      {
        cid: data.cid,
        filePath: data.filePath,
        name: '临时上传' + new Date().getTime(),
        fileSize: data.size,
        fileName: data.name,
        type: 1,
        width: data.width,
        height: data.height
      }
    )
  }).then(({data}) => {
    if (data && data.code === 0) {
      console.log('已添加素材')
    } else {
    }
  })
  commit(types.PUSH_VIDEO_LIST, data)
}
/**
 * 清除背景
 * @param commit
 */
export const cleanBG = ({commit}) => {
  commit(types.CLEAN_BG)
}

export const cleanEle = ({commit}, ele) => {
  commit(types.CLEAN_ELE, ele)
}
/**
 * 复制页面
 * @param commit
 */
export const copyPage = ({commit}, data) => {
  var page = tools.vue2json(data)
  commit(types.ADD_PAGE, page)
}

/**
 * 删除页面
 * @param commit
 */
export const delPage = ({commit}, page) => {
  commit(types.DELETE_PAGE, page)
}

export const getPageByThemeId = ({dispatch, commit}, data) => {
  api.getPageByThemeId(data.id).then((res) => {
    // console.log('res', res)
    if (data.copy) {
      res.theme.id = null
      res.theme.type = 1
      res.theme.title = '广告' + new Date().pattern('yyyyMMddHHmmss')
      console.log('res.skin', res.theme)
    }
    commit(types.SET_CUR_EDITOR_THEME, res.theme)
    commit(types.SET_CUR_EDITOR_PAGE, res.theme.pages[0])
  }).then(() => {
    dispatch('sortElementsByZindex')
  })
}

export const getPageBySkinId = ({dispatch, commit}, data) => {
  api.getPageBySkinId(data.id).then((res) => {
    console.log('res', res)
    let pages = []
    let page = {elements: res.skin.elements}
    pages.push(page)
    res.skin.pages = pages
    console.log('copy', data.copy)
    if (data.copy) {
      res.skin.id = null
      console.log('res.skin', res.skin)
    }
    commit(types.SET_CUR_EDITOR_THEME, res.skin)
    commit(types.SET_CUR_EDITOR_PAGE, page)
  }).then(() => {
    dispatch('sortElementsByZindex')
  })
}

export const setEditorElement = ({commit}, element) => {
  commit(types.SET_CUR_EDITOR_ELEMENT, element)
}

// 删除元素
export const deleteElement = ({commit}, element) => {
  commit(types.DELETE_ELEMENT, element)
}

export const deleteSelectedElement = ({commit, state}) => {
  commit(types.DELETE_ELEMENT, state.editorElement)
}

export const playAnimate = ({state, commit, getters}) => {
  commit(types.PLAY_ANIMATE)
  let target = getters['editingElement'] || getters['editingPageElements'] || null
  let time = 0
  if (target instanceof Array) {
    target.forEach(v => {
      time = v['animatedName'] && (v['duration'] + v['delay']) > time ? (v['duration'] + v['delay']) : time
    })
  } else if (target instanceof Object) {
    time = (target['duration'] + target['delay'])
  }
  setTimeout(() => {
    commit(types.STOP_ANIMATE, target)
  }, time * 1000)
}

export const getPicListByThemeId = ({commit}, query) => {
  // api.getPicListByThemeId(_id).then((res) => {
  //
  // })
  console.log('getPicListByThemeId')
  httpRequest({
    url: httpRequest.adornUrl('/sys/material/list'),
    method: 'get',
    params: httpRequest.adornParams(query)
  }).then(({data}) => {
    if (data && data.code === 0) {
      commit(types.FETCH_PIC_LIST, data.page)
    } else {
      // alert(data.msg)
      this.$message({
        type: 'error',
        message: data.msg
      })
    }
  })
}
export const getVideoListByThemeId = ({commit}, query) => {
  // api.getVideoListByThemeId(query).then((res) => {
  //   commit(types.FETCH_VIDEO_LIST, res)
  // })
  httpRequest({
    url: httpRequest.adornUrl('/sys/material/list'),
    method: 'get',
    params: httpRequest.adornParams(query)
  }).then(({data}) => {
    if (data && data.code === 0) {
      commit(types.FETCH_VIDEO_LIST, data.page)
    } else {
      // alert(data.msg)
      this.$message({
        type: 'error',
        message: data.msg
      })
    }
  })
}

export const getMusicListByThemeId = ({commit}, query) => {
  // api.getVideoListByThemeId(query).then((res) => {
  //   commit(types.FETCH_VIDEO_LIST, res)
  // })
  httpRequest({
    url: httpRequest.adornUrl('/sys/material/list'),
    method: 'get',
    params: httpRequest.adornParams(query)
  }).then(({data}) => {
    if (data && data.code === 0) {
      commit(types.FETCH_MUSIC_LIST, data.page)
    } else {
      // alert(data.msg)
      this.$message({
        type: 'error',
        message: data.msg
      })
    }
  })
}

export const getTextListByThemeId = ({commit}, query) => {
  httpRequest({
    url: httpRequest.adornUrl('/sys/material/list'),
    method: 'get',
    params: httpRequest.adornParams(query)
  }).then(({data}) => {
    if (data && data.code === 0) {
      commit(types.FETCH_TEXT_LIST, data.page)
    } else {
      // alert(data.msg)
      this.$message({
        type: 'error',
        message: data.msg
      })
    }
  })
}

export const getAnimListByThemeId = ({commit}, query) => {
  httpRequest({
    url: httpRequest.adornUrl('/sys/material/list'),
    method: 'get',
    params: httpRequest.adornParams(query)
  }).then(({data}) => {
    if (data && data.code === 0) {
      commit(types.FETCH_ANIM_LIST, data.page)
    } else {
      // alert(data.msg)
      this.$message({
        type: 'error',
        message: data.msg
      })
    }
  })
}

export const cleanPicList = ({commit}) => {
  commit(types.CLEAN_PIC_LIST)
}

export const sortElementsByZindex = ({commit}, location) => {
  commit(types.SORTELEMENTS_BY_ZINDEX, location)
}

export const deleteTheme = ({commit}, theme) => {
  return Promise.resolve(api.delTheme(theme).then((res) => {
    commit(types.DELETE_THEME, theme)
  }))
}
